import { createRouter, createWebHistory } from "vue-router";
import { useUserInfo } from "@/stores/user.js";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/404",
      name: "notFound",
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import("../views/404.vue"),
    },
    {
      path: "/",
      name: "mian",
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import("../views/index.vue"),
      children: [
        {
          path: "/userManager",
          name: "userManager",
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import("../views/userManager.vue"),
        },
        {
          path: "/swiper",
          name: "swiper",
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import("../views/swiper.vue"),
        },
        {
          path: "/order",
          name: "order",
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import("../views/order.vue"),
        },
        {
          path: "/product",
          name: "product",
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import("../views/product.vue"),
        },
        {
          path: "/",
          redirect: "/userManager",
        },
        {
          path: "*",
          redirect: "/404",
        },
      ],
    },
  ],
});

const pageList = ["/login", "/404"];

router.beforeEach((to, from, next) => {
  const store = useUserInfo();
  // console.log(store.token);
  if (store.token) {
    if (to.path.toLowerCase() === "/login") {
      next("/");
    } else {
      next();
    }
  } else {
    if (pageList.includes(to.path.toLowerCase())) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
